﻿'============================================
' MainDockGrid.vb
' by Ken T Ekeoha
'============================================





Public Class MainDockGrid : Inherits Grid


#Region "PROPs"
    Public MainGrid As Grid
    Dim PinMainGrid As PinningGrid
    Dim FrameDimensions As Thickness = New Thickness(20, 20, 20, 20)

    Dim TotalGrids As List(Of Grid)
    Dim UnPinnedGrids As List(Of Grid)

    Dim helperGrid As DockHelperGrid
    Public helperGridWindow As DockHelperInterface


    Dim LeftButtons As ScrollViewer
    Dim RightButtons As ScrollViewer
    Dim TopButtons As ScrollViewer
    Dim BottomButtons As ScrollViewer


    Public Property MDGTabsStyle As Style
        Get
            Return GetValue(MDGTabsStyleProperty)
        End Get

        Set(ByVal value As Style)
            SetValue(MDGTabsStyleProperty, value)
        End Set
    End Property

    Public Shared ReadOnly MDGTabsStyleProperty As DependencyProperty = _
                           DependencyProperty.Register("MDGTabsStyle", _
                           GetType(Style), GetType(MainDockGrid), _
                           New FrameworkPropertyMetadata())
    'Public Property MDGWindowsBannerActivatedStyle As Style
    '    Get
    '        Return GetValue(MDGWindowsBannerActivatedStyleProperty)
    '    End Get

    '    Set(ByVal value As Style)
    '        SetValue(MDGWindowsBannerActivatedStyleProperty, value)
    '    End Set
    'End Property

    'Public Shared ReadOnly MDGWindowsBannerActivatedStyleProperty As DependencyProperty = _
    '                       DependencyProperty.Register("MDGWindowsBannerActivatedStyle", _
    '                       GetType(Style), GetType(KBanner), _
    '                       New FrameworkPropertyMetadata())

    Public Property MDGBannersStyle As Style
        Get
            Return GetValue(MDGBannersStyleProperty)
        End Get

        Set(ByVal value As Style)
            SetValue(MDGBannersStyleProperty, value)
        End Set
    End Property

    Public Shared ReadOnly MDGBannersStyleProperty As DependencyProperty = _
                           DependencyProperty.Register("MDGBannersStyle", _
                           GetType(Style), GetType(MainDockGrid), _
                           New FrameworkPropertyMetadata())


    Public Property MDGBannersButtonsStyle As Style
        Get
            Return GetValue(MDGBannersButtonsStyleProperty)
        End Get

        Set(ByVal value As Style)
            SetValue(MDGBannersButtonsStyleProperty, value)
        End Set
    End Property

    Public Shared ReadOnly MDGBannersButtonsStyleProperty As DependencyProperty = _
                           DependencyProperty.Register("MDGBannersButtonsStyle", _
                           GetType(Style), GetType(MainDockGrid), _
                           New FrameworkPropertyMetadata())


    Public Enum DockPosition
        Left = 0
        Top = 1
        Right = 2
        Bottom = 4
        Center = 8

        Null = 16
    End Enum

#End Region

#Region "c.tor"
    Public Sub New()
        '  Dim mainGridGrid As New KGrid()
        TotalGrids = New List(Of Grid)
        UnPinnedGrids = New List(Of Grid)


        'Arrange Main Grid
        MainGrid = New Grid()
        MainGrid.Margin = FrameDimensions
        MainGrid.Background = Brushes.Transparent


        MainGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        MainGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch

        'AddHandler b2.Click, AddressOf onClick_3
        '   TotalGrids.Add(mainGridGrid)

        '  MainGrid.Children.Add(mainGridGrid)
        Me.Children.Add(MainGrid)



        'IL GRID PER GLI UNPINNEDGRIDS
        PinMainGrid = New PinningGrid(Me)
        ' PinMainGrid.Visibility = Windows.Visibility.Collapsed
        ' PinMainGrid.Background = Nothing
        PinMainGrid.Margin = FrameDimensions

        '  AddHandler PinMainGrid.LostFocus, AddressOf OnUnPinnedGridLostFocus
        '   AddHandler PinMainGrid.MouseLeave, AddressOf OnUnPinnedGridMouseLeave

        'crea la suddivisione del pinMainGrid
       
        Me.Children.Add(PinMainGrid)



        'TODO: Commit al 13.01 -> 6-5-2012
        LeftButtons = New ScrollViewer
        LeftButtons.Width = FrameDimensions.Left
        LeftButtons.VerticalAlignment = Windows.VerticalAlignment.Stretch
        LeftButtons.HorizontalAlignment = Windows.HorizontalAlignment.Left
        LeftButtons.Background = Brushes.Transparent
        LeftButtons.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden
        LeftButtons.Margin = New Thickness(0, FrameDimensions.Top, 0, 0)
        Dim stackLeft As New StackPanel
        LeftButtons.Content = stackLeft
        stackLeft.Orientation = Orientation.Horizontal
        stackLeft.LayoutTransform = New RotateTransform(-90)
        stackLeft.FlowDirection = Windows.FlowDirection.RightToLeft
        Children.Add(LeftButtons)

        RightButtons = New ScrollViewer
        RightButtons.Width = FrameDimensions.Right
        RightButtons.VerticalAlignment = Windows.VerticalAlignment.Stretch
        RightButtons.HorizontalAlignment = Windows.HorizontalAlignment.Right
        RightButtons.Background = Brushes.Transparent
        RightButtons.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden
        RightButtons.Margin = New Thickness(0, FrameDimensions.Top, 0, 0)
        Dim stackRight As New StackPanel
        stackRight.Orientation = Orientation.Horizontal
        stackRight.LayoutTransform = New RotateTransform(90)
        RightButtons.Content = stackRight
        Children.Add(RightButtons)

        BottomButtons = New ScrollViewer
        BottomButtons.Height = FrameDimensions.Bottom
        BottomButtons.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        BottomButtons.VerticalAlignment = Windows.VerticalAlignment.Bottom
        BottomButtons.Background = Brushes.Transparent
        BottomButtons.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled
        BottomButtons.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden
        BottomButtons.Margin = New Thickness(FrameDimensions.Left, 0, FrameDimensions.Right, 0)
        Dim stackBottom As New StackPanel
        stackBottom.Orientation = Orientation.Horizontal
        BottomButtons.Content = stackBottom
        Children.Add(BottomButtons)

        TopButtons = New ScrollViewer
        TopButtons.Width = Double.NaN
        TopButtons.Height = FrameDimensions.Top
        TopButtons.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        TopButtons.VerticalAlignment = Windows.VerticalAlignment.Top
        TopButtons.Background = Brushes.Transparent
        TopButtons.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled
        TopButtons.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden
        Dim stackTop As New StackPanel
        stackTop.Orientation = Orientation.Horizontal
        TopButtons.Content = stackTop
        Children.Add(TopButtons)

    End Sub
#End Region

    Protected Overrides Sub OnInitialized(ByVal e As System.EventArgs)

        MyBase.OnInitialized(e)

        Application.Current.Properties.Add("MDGToken", New MainDockGridToken(Me))    'TODO: Attenzione - 15 : Con questo Token tutte le KWindow sapranno dell'esistenza di un MainDockGrid su Cui dockare.

    End Sub




    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="gr"></param>
    ''' <returns>Il grid mega parente o altrimenti abbiamo Nothing.</returns>
    ''' <remarks></remarks>
    Public Function GetAvus(ByRef gr As Grid) As Grid
      


        'Per ora mi aspetto che il grid Avo di tutti i grid che non sia MainGrid è il FIGLIO DI MAINGRID. E sono sicuro che 
        'Maingrid ne possiede solo uno.

        Return MainGrid.Children(0)

    End Function


    Public Sub AddCard(ByRef TargetGrid As Grid, ByVal Position As DockPosition)
        If Position = DockPosition.Left Or Position = DockPosition.Right Then
            AddCardLeftRight(TargetGrid, Position)
        Else
            AddCardTopBottom(TargetGrid, Position)
        End If
    End Sub

    Protected Overridable Sub AddCardLeftRight(ByRef TargetGrid As Grid, ByVal Position As DockPosition)
        'from right
        Dim detachedGrid As Grid
        If TargetGrid.Children.Count = 0 Then
            TargetGrid.Children.Add(New Grid)
        End If
        detachedGrid = TargetGrid.Children(0)

        Dim parent As Grid = DirectCast(detachedGrid.Parent, Grid)
        'LastDetachedGridID = New GridID(Grid.GetColumn(detachedGrid), Grid.GetRow(detachedGrid), parent)    '
        'detachingPending = True
        parent.Children.Remove(detachedGrid)   'stacca il grid     -   detaches the grid

        Dim g As New Grid
        g.Width = Double.NaN
        g.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        g.VerticalAlignment = Windows.VerticalAlignment.Stretch
        '   g.Background = Brushes.Green

        g.ColumnDefinitions.Add(Yield_Column(20))
        g.ColumnDefinitions.Add(Yield_Column(20))



        Dim newGrid As New KGrid(Me)
        newGrid.Title = "empty." & TotalGrids.Count - 1
        newGrid.Width = Double.NaN
        newGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        newGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch
        ' newGrid.Background = Brushes.Orange

        If Position = DockPosition.Left Then
            Grid.SetColumn(detachedGrid, 1)
            Grid.SetColumn(newGrid, 0)
        ElseIf Position = DockPosition.Right Then
            Grid.SetColumn(detachedGrid, 0)
            Grid.SetColumn(newGrid, 1)
        End If


        Dim gs As GridSplitter = Yield_LeftRightGridSplitter()
        Grid.SetColumn(gs, 1)

        '  g.InvalidateArrange()
        g.Children.Add(newGrid)
        g.Children.Add(detachedGrid)
        g.Children.Add(gs)

        TargetGrid.Children.Add(g)

        'TotalGrids.Add(g)
        If Not TotalGrids.Contains(newGrid) Then
            ' AddHandler newGrid.Grip.MouseUp, AddressOf OnGridMouseUp
            ' AddHandler newGrid.Grip.MouseMove, AddressOf OnGridMouseMove
            newGrid.State = KGrid.KGridState.Docked
            TotalGrids.Add(newGrid)
        End If
    End Sub

    Protected Overridable Sub AddCardTopBottom(ByRef TargetGrid As Grid, ByVal Position As DockPosition)
        'from right

        Dim detachedGrid As Grid
        If TargetGrid.Children.Count = 0 Then
            detachedGrid = TargetGrid
        Else
            detachedGrid = TargetGrid.Children(0)
        End If



        Dim parent As Grid = DirectCast(detachedGrid.Parent, Grid)
        'LastDetachedGridID = New GridID(Grid.GetColumn(detachedGrid), Grid.GetRow(detachedGrid), parent)    '
        'detachingPending = True
        parent.Children.Remove(detachedGrid)   'stacca il grid     -   detaches the grid

        Dim g As New Grid
        g.Height = Double.NaN
        g.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        g.VerticalAlignment = Windows.VerticalAlignment.Stretch
        ' g.Background = Brushes.Blue



        g.RowDefinitions.Add(Yield_Row(20))
        g.RowDefinitions.Add(Yield_Row(20))



        Dim newGrid As New KGrid(Me)
        newGrid.Title = "empty." & TotalGrids.Count - 1
        newGrid.Height = Double.NaN
        newGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        newGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch
        newGrid.Background = Brushes.Red
        ' AddHandler newGrid.Grip.MouseUp, AddressOf OnGridMouseUp
        ' AddHandler newGrid.Grip.MouseMove, AddressOf OnGridMouseMove

        If Position = DockPosition.Top Then
            Grid.SetRow(detachedGrid, 1)
            Grid.SetRow(newGrid, 0)
        ElseIf Position = DockPosition.Bottom Then
            Grid.SetRow(detachedGrid, 0)
            Grid.SetRow(newGrid, 1)
        End If


        'Grid.SetRow(detachedGrid, 0)
        'Grid.SetRow(newGrid, 1)

        g.Children.Add(newGrid)
        g.Children.Add(detachedGrid)

        Dim gs As GridSplitter = Yield_TopBottomGridSplitter()
        Grid.SetRow(gs, 1)
        g.Children.Add(gs)

        TargetGrid.Children.Add(g)

        ' TotalGrids.Add(g)
        If Not TotalGrids.Contains(newGrid) Then
            'AddHandler newGrid.Grip.MouseUp, AddressOf OnGridMouseUp
            ' AddHandler newGrid.Grip.MouseMove, AddressOf OnGridMouseMove
            newGrid.State = KGrid.KGridState.Docked
            TotalGrids.Add(newGrid)
        End If
    End Sub



    Public Sub DockCard(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition, ByRef floatingWindow As Window)

        If TargetGrid Is MainGrid Then
            ForfeitDock(detachedGrid, TargetGrid, Position, floatingWindow.Title)

        Else


            If Position = DockPosition.Left Or Position = DockPosition.Right Then
                DockCardLeftRight(detachedGrid, TargetGrid, Position, floatingWindow.Title)
            ElseIf Position = DockPosition.Top Or Position = DockPosition.Bottom Then
                DockCardTopBottom(detachedGrid, TargetGrid, Position, floatingWindow.Title)
            ElseIf Position = DockPosition.Center Then

                DockCardCenter(detachedGrid, TargetGrid, Position, floatingWindow.Title)
            End If
        End If


        If detachedGrid.Background Is Nothing Then detachedGrid.Background = Brushes.Transparent


        If floatingWindow IsNot Nothing Then
            floatingWindow.Close()
            '   detachedGrid.Grip.RemoveHandler(MouseUpEvent, DirectCast(detachedGrid.Grip.PuppetWindow, MoveableWindow).Grip_MouseUp)
            '  Mouse.RemoveMouseUpHandler(detachedGrid.Grip, DirectCast(detachedGrid.Grip.PuppetWindow, MoveableWindow).onGripButtonEventHandler)
            ' If detachedGrid.Grip.PuppetWindow Is floatingWindow Then detachedGrid.Grip.PuppetWindow = Nothing
        End If
    End Sub

    ''' <summary>
    ''' Ancora un Grid - non ancora staccato - Senza Finestra.
    ''' </summary>
    ''' <param name="detachedGrid"></param>
    ''' <param name="TargetGrid"></param>
    ''' <param name="Position"></param>
    ''' <remarks></remarks>
    Public Sub DockCard(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition)


        If TargetGrid Is MainGrid Then
            ForfeitDock(detachedGrid, TargetGrid, Position, detachedGrid.Title)

        Else


            If Position = DockPosition.Left Or Position = DockPosition.Right Then
                DockCardLeftRight(detachedGrid, TargetGrid, Position, detachedGrid.Title)
            ElseIf Position = DockPosition.Top Or Position = DockPosition.Bottom Then
                DockCardTopBottom(detachedGrid, TargetGrid, Position, detachedGrid.Title)
            ElseIf Position = DockPosition.Center Then
                DockCardCenter(detachedGrid, TargetGrid, Position, detachedGrid.Title)
            End If
        End If
        If detachedGrid.Background Is Nothing Then detachedGrid.Background = Brushes.Transparent


    End Sub

    Protected Overridable Sub DockCardLeftRight(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition, Optional ByVal _title As String = "")
        Dim winTitle As String = _title
        ' If winTitle IsNot Nothing Then winTitle = floatingWindow.Title

        If detachedGrid.Parent IsNot Nothing Then DirectCast(detachedGrid.Parent, Grid).Children.Remove(detachedGrid) 'stacca il grid     -   detaches the grid

        'per adesso TargetGrid = BrotherGrid 17.42
        Dim parentGrid = DirectCast(TargetGrid.Parent, Grid)

        Dim TargetGridColumn As Integer = Grid.GetColumn(TargetGrid)
        Dim TargetGridRow As Integer = Grid.GetRow(TargetGrid)

        parentGrid.Children.Remove(TargetGrid)



        Dim CarrierGrid As New Grid
        CarrierGrid.Width = Double.NaN
        CarrierGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        CarrierGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch
        '  CarrierGrid.Background = Brushes.Green
        CarrierGrid.ColumnDefinitions.Add(Yield_Column(20))
        CarrierGrid.ColumnDefinitions.Add(Yield_Column(20))

        ' AddHandler detachedGrid.MouseUp, AddressOf OnGridMouseUp
        '   AddHandler detachedGrid.MouseMove, AddressOf OnGridMouseMove

        If Position = DockPosition.Left Then
            Grid.SetColumn(TargetGrid, 1)
            Grid.SetColumn(detachedGrid, 0)
            detachedGrid.State = KGrid.KGridState.Docked + KGrid.KGridState.L
        ElseIf Position = DockPosition.Right Then
            Grid.SetColumn(TargetGrid, 0)
            Grid.SetColumn(detachedGrid, 1)
            detachedGrid.State = KGrid.KGridState.Docked + KGrid.KGridState.R
        End If
        Grid.SetColumn(CarrierGrid, TargetGridColumn)
        Grid.SetRow(CarrierGrid, TargetGridRow)

        CarrierGrid.Children.Add(TargetGrid)
        CarrierGrid.Children.Add(detachedGrid)

        Dim gs As GridSplitter = Yield_LeftRightGridSplitter()
        Grid.SetColumn(gs, 1)
        CarrierGrid.Children.Add(gs)

        'TODO: Dato che grid splitter del ex-parente di detachedGrid si trova nello stesso quadrante di carrierGrid, verrà nascosto sotto di lui. Bisogna o spostare in avanti gridSplitter o spostare indietro CarrierGrid.
        'sposto i gridplitter in avanti.

        parentGrid.Children.Add(CarrierGrid)

        If Not TotalGrids.Contains(detachedGrid) Then

            ' detachedGrid.State = KGrid.KGridState.Docked
            detachedGrid.Grip.PuppetWindow = Nothing
            TotalGrids.Add(detachedGrid)

        End If



    End Sub

    Protected Overridable Sub DockCardTopBottom(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition, Optional ByVal _title As String = "")
        Dim winTitle As String = _title

        If detachedGrid.Parent IsNot Nothing Then DirectCast(detachedGrid.Parent, Grid).Children.Remove(detachedGrid) 'stacca il grid     -   detaches the grid

        'per adesso TargetGrid = BrotherGrid 17.42
        Dim parentGrid = DirectCast(TargetGrid.Parent, Grid)
        Dim TargetGridRow As Integer = Grid.GetRow(TargetGrid)
        Dim TargetGridColumn As Integer = Grid.GetColumn(TargetGrid)
        parentGrid.Children.Remove(TargetGrid)

        Dim CarrierGrid As New Grid
        CarrierGrid.Width = Double.NaN
        CarrierGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        CarrierGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch
        '   CarrierGrid.Background = Brushes.Green


        CarrierGrid.RowDefinitions.Add(Yield_Row(20))
        CarrierGrid.RowDefinitions.Add(Yield_Row(20))

        Dim gs As GridSplitter
        If Position = DockPosition.Top Then
            Grid.SetRow(TargetGrid, 1)
            Grid.SetRow(detachedGrid, 0)
            detachedGrid.State = KGrid.KGridState.Docked + KGrid.KGridState.T

        ElseIf Position = DockPosition.Bottom Then
            Grid.SetRow(TargetGrid, 0)
            Grid.SetRow(detachedGrid, 1)
            detachedGrid.State = KGrid.KGridState.Docked + KGrid.KGridState.B
        End If

        gs = Yield_TopBottomGridSplitter()


        Grid.SetColumn(CarrierGrid, TargetGridColumn)
        Grid.SetRow(CarrierGrid, TargetGridRow)
        Grid.SetRow(gs, 1)

        CarrierGrid.Children.Add(TargetGrid)
        CarrierGrid.Children.Add(detachedGrid)
        CarrierGrid.Children.Add(gs)

        parentGrid.Children.Add(CarrierGrid)

        If Not TotalGrids.Contains(detachedGrid) Then
            ' AddHandler detachedGrid.Grip.MouseUp, AddressOf OnGridMouseUp
            ' AddHandler detachedGrid.Grip.MouseMove, AddressOf OnGridMouseMove
            'detachedGrid.State = KGrid.KGridState.Docked
            detachedGrid.Grip.PuppetWindow = Nothing
            TotalGrids.Add(detachedGrid)
        End If

    End Sub


    Protected Overridable Sub DockCardCenter(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition, Optional ByVal _title As String = "")



        If TypeOf (TargetGrid) Is CentrKGrid Then

            Dim winTitle As String = _title
            If detachedGrid.Parent IsNot Nothing Then DirectCast(detachedGrid.Parent, Grid).Children.Remove(detachedGrid) 'stacca il grid     -   detaches the grid

            DirectCast(TargetGrid, CentrKGrid).AddTab(detachedGrid)

            TotalGrids.Remove(detachedGrid)
            ' TotalGrids.Remove(TargetGrid)


            detachedGrid.State = KGrid.KGridState.Docked
            detachedGrid.Grip.PuppetWindow = Nothing

            If Not TotalGrids.Contains(TargetGrid) Then
                TotalGrids.Add(TargetGrid)
            End If
        Else

            Dim winTitle As String = _title

            If detachedGrid.Parent IsNot Nothing Then DirectCast(detachedGrid.Parent, Grid).Children.Remove(detachedGrid) 'stacca il grid     -   detaches the grid

            'per adesso TargetGrid = BrotherGrid 17.42
            Dim parentGrid = DirectCast(TargetGrid.Parent, Grid)
            Dim TargetGridColumn As Integer = Grid.GetColumn(TargetGrid)
            Dim TargetGridRow As Integer = Grid.GetRow(TargetGrid)
            parentGrid.Children.Remove(TargetGrid)

            Dim CarrierGrid As New CentrKGrid(Me)
            CarrierGrid.Width = Double.NaN
            CarrierGrid.HorizontalAlignment = Windows.HorizontalAlignment.Stretch
            CarrierGrid.VerticalAlignment = Windows.VerticalAlignment.Stretch
            ' CarrierGrid.Background = Brushes.Green
            CarrierGrid.State = KGrid.KGridState.Docked

            Grid.SetRow(CarrierGrid, TargetGridRow)
            Grid.SetColumn(CarrierGrid, TargetGridColumn)

            CarrierGrid.AddTab(TargetGrid)
            CarrierGrid.AddTab(detachedGrid)

            parentGrid.Children.Add(CarrierGrid)

            ' If TotalGrids.Contains(detachedGrid) Then
            TotalGrids.Remove(detachedGrid)
            TotalGrids.Remove(TargetGrid)
            'End If
            detachedGrid.State = KGrid.KGridState.Docked
            detachedGrid.Grip.PuppetWindow = Nothing

            If Not TotalGrids.Contains(CarrierGrid) Then
                TotalGrids.Add(CarrierGrid)
            End If

        End If
    End Sub

    Private Sub ForfeitDock(ByRef detachedGrid As KGrid, ByRef TargetGrid As Grid, ByVal Position As DockPosition, Optional ByVal _title As String = "")

        ' If TargetGrid Is MainGrid Then      'questo può avvenire solo se si sta tentando di dockare una window su Un MainDockGrid vuoto, ovvero con solo Maingrid come figlio.
        If detachedGrid.Parent IsNot Nothing Then DirectCast(detachedGrid.Parent, Grid).Children.Remove(detachedGrid)

        MainGrid.Children.Add(detachedGrid)
        detachedGrid.State = KGrid.KGridState.Docked
        TotalGrids.Add(detachedGrid)
        Return
        ' End If
    End Sub


    Public Function MyBoundsContainsPoint(ByVal pToScreen As Point)
        Dim p1 As Point = PointToScreen(New Point(0, 0))
        Dim p2 As Point = PointToScreen(New Point(ActualWidth, ActualHeight))

        Return p1.X <= pToScreen.X And pToScreen.X <= p2.X And p1.Y <= pToScreen.Y And pToScreen.Y <= p2.Y
    End Function

    Dim _parentWindow As Window
    Public Function ParentWindow() As Window
        If _parentWindow IsNot Nothing Then Return _parentWindow

        Dim p As DependencyObject = Parent

        Do Until TypeOf (p) Is Window
            p = LogicalTreeHelper.GetParent(p)
        Loop

        Return p
    End Function

    Public Sub AdoptMoveableWindow(ByRef win As MoveableWindow)
        win.Owner = ParentWindow()
    End Sub

    Public Sub AbandonMoveableWindow(ByRef win As MoveableWindow)
        If (win.Owner Is _parentWindow) Then
            win.Owner = Nothing       'TODO: Attenzione 16- Non so se poi la finestra verrà rimossa anche dalla lista OwnedWindows.
        End If
    End Sub

    Public Sub OnGridMouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        '  FloatGrid_Ex(DirectCast(DirectCast(sender, GripLabel).Parent, KGrid))
    End Sub

    Protected Sub OnGridMouseMove(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
        '   TestGrid(PointToScreen(Mouse.GetPosition(Me)))
    End Sub


    Public Sub ShiftGizmo(ByVal pToScreen As Point)
        Dim pt As Point = PointFromScreen(pToScreen)
        ' GridRect = Nothing
        'se il punto non si trova all'interno della regione compresa da MainDockGrid non ha senso cercare altri punti.

        If Not (pt.X >= 0 And pt.X < ActualWidth) Then Return
        If Not (pt.Y >= 0 And pt.Y < ActualHeight) Then Return

        helperGrid.MoveInnerGizmo(MainGrid)

        For x = 0 To TotalGrids.Count - 1
            pt = TotalGrids(x).PointFromScreen(pToScreen)
            If pt.X >= 0 And pt.X < TotalGrids(x).ActualWidth Then
                If pt.Y >= 0 And pt.Y < TotalGrids(x).ActualHeight Then
                    helperGrid.MoveInnerGizmo(TotalGrids(x))
                    Return
                End If
            End If
        Next

    End Sub

    Public Function StartDockingProcedure(ByVal pToScreen As Point, ByRef targetG As Grid) As DockPosition
        Dim dckPos As DockPosition = helperGrid.ProcessDockingPointRequest(pToScreen, targetG)
        Return dckPos
    End Function

    ''' <summary>
    ''' Ottiene il grid più in basso nella gerarchia, che appartenga a TotalGrids.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetVeryBaseGrid()
        If MainGrid.Children.Count > 0 Then Return MainGrid.Children(0) Else Return MainGrid
    End Function



    Public Function Yield_LeftRightGridSplitter()
        Dim splitter As GridSplitter
        splitter = New GridSplitter
        splitter.HorizontalAlignment = Windows.HorizontalAlignment.Left
        splitter.Width = 2
        splitter.ShowsPreview = True
        splitter.Margin = New Thickness(0, 0, 0, 0)
        splitter.Background = Brushes.Transparent
        splitter.VerticalAlignment = Windows.VerticalAlignment.Stretch
        Panel.SetZIndex(splitter, 2)        'TODO: Informazione - 19 :assicura che il grid Splitter si veda sopra il resto.
        '   Grid.SetColumn(splitter, Math.Max(0, MainGrid.ColumnDefinitions.Count - 2))
        Return splitter
    End Function

    Public Function Yield_TopBottomGridSplitter()
        Dim splitter As GridSplitter
        splitter = New GridSplitter
        splitter.VerticalAlignment = Windows.VerticalAlignment.Top
        splitter.Height = 2
        splitter.ShowsPreview = True
        splitter.Background = Brushes.Transparent
        splitter.HorizontalAlignment = Windows.VerticalAlignment.Stretch
        splitter.Margin = New Thickness(0, 0, 0, 0)
        Panel.SetZIndex(splitter, 2)
        'Grid.SetRow(splitter, Math.Max(0, MainGrid.RowDefinitions.Count - 2))
        Return splitter
    End Function

    Public Function Yield_Row(ByVal minH As Double) As RowDefinition
        Dim r As New RowDefinition
        r.MinHeight = minH
        Return r
    End Function

    Public Function Yield_Column(ByVal minW As Double) As ColumnDefinition
        Dim r As New ColumnDefinition
        r.MinWidth = minW
        Return r
    End Function


    ''' <summary>
    ''' Stacca un grid dockato dal parente ma non lo mostra in una KWindow
    ''' </summary>
    ''' <param name="inputGrid"></param>
    ''' <remarks></remarks>
    Public Sub DetachDockedGrid(ByRef inputGrid As KGrid)
        If Not TotalGrids.Contains(inputGrid) Then Return

        Dim parentGrid As Grid = inputGrid.Parent

        parentGrid.Children.Remove(inputGrid)
        TotalGrids.Remove(inputGrid)

        Dim gridBrothers As Integer
        For x = 0 To parentGrid.Children.Count - 1
            If TypeOf (parentGrid.Children(x)) Is Grid Then
                gridBrothers += 1
            End If
        Next

        If gridBrothers = 1 Then

            Dim otherGrid As New Grid


            'toglie gli splitter
            For x = parentGrid.Children.Count - 1 To 0 Step -1
                If TypeOf (parentGrid.Children(x)) Is GridSplitter Then
                    parentGrid.Children.RemoveAt(x)
                    x -= 1
                End If
                If TypeOf (parentGrid.Children(x)) Is Grid Then
                    otherGrid = parentGrid.Children(x)
                    Grid.SetColumn(otherGrid, Grid.GetColumn(parentGrid))
                    Grid.SetRow(otherGrid, Grid.GetRow(parentGrid))
                    parentGrid.Children.Remove(otherGrid)
                    x -= 1
                End If
            Next
            'scambia il parente con l'altro
            Dim grandpa As Grid = parentGrid.Parent
            grandpa.Children.Remove(parentGrid)
            grandpa.Children.Add(otherGrid)

            'da quando uso i banner, othergrid, tende ad avere rowspan di 2+, perciò devo farlo tornare ad un valore normale di uno.
            Grid.SetRowSpan(otherGrid, 1)   'TODO : Informazione - 16 : Questo è un SetRowSpan di grado 1, che serve per patchare in altre situazioni.
            parentGrid = Nothing



        ElseIf gridBrothers = 0 Then



            'toglie il figlio
            'parentGrid.Children.Remove(grid)
            'TotalGrids.Remove(grid)
            'RemoveHandler grid.MouseMove, AddressOf OnGridMouseMove
            'RemoveHandler grid.MouseUp, AddressOf OnGridMouseUp



            'toglie gli splitter
            For x = parentGrid.Children.Count - 1 To 0 Step -1
                If TypeOf (parentGrid.Children(x)) Is GridSplitter Then
                    parentGrid.Children.RemoveAt(x)
                End If
            Next

            If parentGrid IsNot MainGrid Then
                Dim grandpa As Grid = parentGrid.Parent     'rimuove anche il grid padre, dal grid nonno perchè in questo punto della funzione sappiamo che il grid padre possiede solo un grid: inputgrid (già rimosso). 
                'Questo vale in generale, ma se inputgrid è figlio diretto di MainGrid questa funzione eliminerebbe anche Maingrid, cerchiamo di evitare questa cosa impedendo l'eliminazione di MainGrid. 

                grandpa.Children.Remove(parentGrid)
                parentGrid = Nothing
            End If

            '  grandpa.Children.Add(grid)
        ElseIf gridBrothers > 1 Then
            MessageBox.Show("Non dovresti leggermi. Ken, hai fatto una cazzata nel codice. Riguarda.")
        End If

    End Sub


    Public Sub second_old_Unpin(ByRef gr As KGrid, ByVal side As DockPosition)

        'deve essere visibile solo uno dei grid ad un dato momento. Non tutti contemporaneamente.

        'vediamo se a questo UnpinnedGrid appartengono già altri grid|windows. Se ci sono devono essere resi invisibli. = Collapsed.
        'For x = 0 To PinMainGrid.LRGrid.Children.Count - 1
        '    If TypeOf (PinMainGrid.Children(x)) Is Grid Then
        '        DirectCast(PinMainGrid.Children(x), Grid).Visibility = Windows.Visibility.Collapsed
        '        Panel.SetZIndex(DirectCast(PinMainGrid.Children(x), Grid), 0)
        '    End If

        '    'sfruttiamo questo loop anche per rimuove tutti i grid Splitter.
        'Next

        'For x = 0 To PinMainGrid.TBGrid.Children.Count - 1
        '    If TypeOf (PinMainGrid.Children(x)) Is Grid Then
        '        DirectCast(PinMainGrid.Children(x), Grid).Visibility = Windows.Visibility.Collapsed
        '        Panel.SetZIndex(DirectCast(PinMainGrid.Children(x), Grid), 0)
        '    End If

        '    'sfruttiamo questo loop anche per rimuove tutti i grid Splitter.
        'Next

        If PinMainGrid.CurrentlyVisibleGrid Is Nothing Then
            PinMainGrid.CurrentlyVisibleGrid = gr
        End If

        If PinMainGrid.CurrentlyVisibleGrid.IsVisible Then
            PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
        End If

        Dim avus As Grid = GetAvus(gr)
        'se malauaguratamente questo grid già apparteneva a maingrid.children(0)
        DetachDockedGrid(gr)

        Select Case side
            Case DockPosition.Left

                Grid.SetColumn(gr, 0)
                PinMainGrid.LRGrid.Children.Add(gr)
            Case DockPosition.Right

                Grid.SetColumn(gr, 2)
                PinMainGrid.LRGrid.Children.Add(gr)
            Case DockPosition.Top

                Grid.SetRow(gr, 0)
                PinMainGrid.TBGrid.Children.Add(gr)
            Case DockPosition.Bottom

                Grid.SetRow(gr, 2)
                PinMainGrid.TBGrid.Children.Add(gr)
            Case DockPosition.Center
                'comportati come se fosse DockPosition.Left .
            Case Else

        End Select

        '  Grid.SetColumnSpan(gr, 1)
        ' Grid.SetRowSpan(gr, 1)
        '  PinMainGrid.Children.Add(gs)    'aggiunge il grid splitte.r
        '  PinMainGrid.Children.Add(gr)        'aggiunge il grid.

        UnPinnedGrids.Add(gr)

        PinMainGrid.Visibility = Windows.Visibility.Visible
        Panel.SetZIndex(gr, 1)
        'ottiene l'avo è la posizione 

        Dim handleButton As KButton = New KButton
        Select Case side
            Case DockPosition.Left
                DirectCast(LeftButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Right
                DirectCast(RightButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Bottom
                DirectCast(BottomButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Top
                DirectCast(TopButtons.Content, StackPanel).Children.Add(handleButton)

        End Select

        handleButton.Content = gr.Title

        handleButton.AttachedKGrid = gr
        gr._AttachedHandleButton = handleButton

        AddHandler handleButton.Click, AddressOf OnHandleButtonClick
        AddHandler handleButton.MouseEnter, AddressOf OnHandleButtonMouseEnter


        handleButton.HorizontalAlignment = Windows.HorizontalAlignment.Center
        handleButton.VerticalAlignment = Windows.VerticalAlignment.Center


        gr.Visibility = Windows.Visibility.Collapsed

    End Sub

    Public Sub Unpin(ByRef gr As KGrid, ByVal side As DockPosition)

        If PinMainGrid.CurrentlyVisibleGrid Is Nothing Then
            PinMainGrid.CurrentlyVisibleGrid = gr
        End If

        If PinMainGrid.CurrentlyVisibleGrid.IsVisible Then
            PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
        End If


        Dim avus As Grid = GetAvus(gr)
        'se malauaguratamente questo grid già apparteneva a maingrid.children(0)
        DetachDockedGrid(gr)

        Select Case side
            Case DockPosition.Left

                Grid.SetColumn(gr, 0)
                PinMainGrid.LRGrid.Children.Add(gr)
                gr.State = KGrid.KGridState.L + KGrid.KGridState.Unpinned + KGrid.KGridState.Soft
            Case DockPosition.Right

                Grid.SetColumn(gr, 2)
                PinMainGrid.LRGrid.Children.Add(gr)
                gr.State = KGrid.KGridState.R + KGrid.KGridState.Unpinned + KGrid.KGridState.Soft
            Case DockPosition.Top

                Grid.SetRow(gr, 0)
                PinMainGrid.TBGrid.Children.Add(gr)
                gr.State = KGrid.KGridState.T + KGrid.KGridState.Unpinned + KGrid.KGridState.Soft
            Case DockPosition.Bottom

                Grid.SetRow(gr, 2)
                PinMainGrid.TBGrid.Children.Add(gr)
                gr.State = KGrid.KGridState.B + KGrid.KGridState.Unpinned + KGrid.KGridState.Soft
            Case DockPosition.Center
                'comportati come se fosse DockPosition.Left .
            Case Else

        End Select

        UnPinnedGrids.Add(gr)


        Panel.SetZIndex(gr, 1)
        '   PinMainGrid.Visibility = Windows.Visibility.Visible

        'ottiene l'avo è la posizione 

        Dim handleButton As KButton = New KButton

        Select Case side
            Case DockPosition.Left
                DirectCast(LeftButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Right
                DirectCast(RightButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Bottom
                DirectCast(BottomButtons.Content, StackPanel).Children.Add(handleButton)

            Case DockPosition.Top
                DirectCast(TopButtons.Content, StackPanel).Children.Add(handleButton)

        End Select


        handleButton.Content = gr.Title
        handleButton.AttachedKGrid = gr
        gr._AttachedHandleButton = handleButton


        AddHandler handleButton.Click, AddressOf OnHandleButtonClick
        AddHandler handleButton.MouseEnter, AddressOf OnHandleButtonMouseEnter


        handleButton.HorizontalAlignment = Windows.HorizontalAlignment.Center
        handleButton.VerticalAlignment = Windows.VerticalAlignment.Center

        ' -----------> Inietta il Templato ------>
        If GetValue(MDGTabsStyleProperty) IsNot Nothing Then
            handleButton.Style = GetValue(MDGTabsStyleProperty)
        End If

        gr.Visibility = Windows.Visibility.Collapsed

    End Sub


    Public Sub OnHandleButtonClick(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        PinMainGrid.SplitterL.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterR.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterB.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterT.Visibility = Windows.Visibility.Collapsed

        If PinMainGrid.CurrentlyVisibleGrid IsNot Nothing Then
            PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
            DirectCast(PinMainGrid.CurrentlyVisibleGrid.Parent, UIElement).Visibility = Windows.Visibility.Collapsed
           
        End If

        PinMainGrid.Visibility = Windows.Visibility.Visible

        PinMainGrid.CurrentlyVisibleGrid = sender.AttachedKGrid
        PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Visible
        DirectCast(PinMainGrid.CurrentlyVisibleGrid.Parent, UIElement).Visibility = Windows.Visibility.Visible
        PinMainGrid.CurrentlyVisibleGrid.State = KGrid.GetLTRB(PinMainGrid.CurrentlyVisibleGrid) + KGrid.KGridState.Unpinned + KGrid.KGridState.Hard


        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.L) Then
            PinMainGrid.SplitterL.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.T) Then
            PinMainGrid.SplitterT.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.R) Then
            PinMainGrid.SplitterR.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.B) Then
            PinMainGrid.SplitterB.Visibility = Windows.Visibility.Visible
        End If

    End Sub

    Private Sub OnHandleButtonMouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
        PinMainGrid.SplitterL.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterR.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterB.Visibility = Windows.Visibility.Collapsed
        PinMainGrid.SplitterT.Visibility = Windows.Visibility.Collapsed


        If PinMainGrid.CurrentlyVisibleGrid IsNot Nothing Then
            PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
            DirectCast(PinMainGrid.CurrentlyVisibleGrid.Parent, UIElement).Visibility = Windows.Visibility.Collapsed
        End If

        PinMainGrid.Visibility = Windows.Visibility.Visible


        PinMainGrid.CurrentlyVisibleGrid = sender.AttachedKGrid
        PinMainGrid.CurrentlyVisibleGrid.Visibility = Windows.Visibility.Visible
        DirectCast(PinMainGrid.CurrentlyVisibleGrid.Parent, UIElement).Visibility = Windows.Visibility.Visible
        PinMainGrid.CurrentlyVisibleGrid.State = KGrid.GetLTRB(PinMainGrid.CurrentlyVisibleGrid) + KGrid.KGridState.Unpinned + KGrid.KGridState.Soft

        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.L) Then
            PinMainGrid.SplitterL.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.T) Then
            PinMainGrid.SplitterT.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.R) Then
            PinMainGrid.SplitterR.Visibility = Windows.Visibility.Visible
        End If
        If PinMainGrid.CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.B) Then
            PinMainGrid.SplitterB.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    Public Sub DetachUnpinnedGrid(ByRef inputGrid As KGrid)       'TODO : Attenzione - 13 : Provvisoria!

        If Not UnPinnedGrids.Contains(inputGrid) Then Return 'se il grid non è unpinnato è impossibile proseguire.

        Dim parentGrid As Grid = inputGrid.Parent

        inputGrid._AttachedHandleButton.AttachedKGrid = Nothing     'il pulsante dimentica grid.
        DirectCast(inputGrid._AttachedHandleButton.Parent, StackPanel).Children.Remove(inputGrid._AttachedHandleButton)     'rimuove il pulsante laterale dell'unpinned card.
        inputGrid._AttachedHandleButton = Nothing       'il grid dimentica il pulsante.

        parentGrid.Children.Remove(inputGrid)
        parentGrid.Visibility = Windows.Visibility.Collapsed    'nasconde il grid a cui apparteneva prima di andarsene ( a scelta tra LRgrid o TBGrid).
        PinMainGrid.CurrentlyVisibleGrid = Nothing      'pinmain dimentica il grid. 
        PinMainGrid.Visibility = Windows.Visibility.Collapsed   'nasconde PinmainGrid.

        UnPinnedGrids.Remove(inputGrid)

    End Sub

    Public Sub DetachKGrid(ByRef inputGrid As KGrid)
        If TotalGrids.Contains(inputGrid) Then
            DetachDockedGrid(inputGrid)
        End If

        If UnPinnedGrids.Contains(inputGrid) Then
            DetachUnpinnedGrid(inputGrid)
        End If
    End Sub

    Public Sub FloatGrid_Ex(ByRef inputGrid As KGrid, Optional ByVal HideNewWindow As Boolean = False)

        DetachKGrid(inputGrid)

        Dim w As New EmptyWindow(Me)
        '   w.Background = Background
        w.InjectedGrid = inputGrid
        inputGrid.State = KGrid.KGridState.Float
        If HideNewWindow Then w.Load() Else w.Show()


    End Sub

    Public Function CalculateUnpinningSide(ByRef inputGrid As KGrid) As DockPosition
        'prima di tutto bisogna assicurarsi che il parente ultimo di inputgrid sia figlio di MainGrid.CHildren(0) (CarrierGrid Primario)
        Dim prnt As DependencyObject = inputGrid
        Dim carrierGrid As Grid = MainGrid.Children(0)      'so che il grid ultimo da ricercare è Il figlio di MainGrid ( figlio di MainDockGrid)
        Do Until carrierGrid.Children.Contains(prnt)
            prnt = LogicalTreeHelper.GetParent(prnt)
        Loop

        Dim totRows As Integer = carrierGrid.RowDefinitions.Count
        Dim totCols As Integer = carrierGrid.ColumnDefinitions.Count
        Dim temp As Integer
        If totRows > 1 And totCols = 0 Then     'topbottom
            temp = Grid.GetRow(prnt)
            If temp = 0 Then
                Return DockPosition.Top
            Else
                Return DockPosition.Bottom
            End If
        End If

        If totCols > 1 And totRows = 0 Then     'leftright
            temp = Grid.GetColumn(prnt)
            If temp = 0 Then
                Return DockPosition.Left
            Else
                Return DockPosition.Right
            End If
        End If

        Return DockPosition.Center
    End Function

    Private Sub MainDockGrid_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        helperGridWindow = New DockHelperInterface(Me)
        Dim pt = PointToScreen(New Point(0, 0))

        helperGridWindow.Width = ActualWidth
        helperGridWindow.Height = ActualHeight

        helperGridWindow.Focusable = False


        helperGrid = helperGridWindow.DHG



    End Sub

    Public Sub UnMaskDockHelperInterface(ByVal HideAllButTheseGizmos As DockHelperGrid.VisibleGizmos)
        helperGridWindow.UnMask(PointToScreen(New Point(0, 0)), New Size(ActualWidth, ActualHeight), HideAllButTheseGizmos)
    End Sub

    Public Sub MaskDockHelperInterface(ByVal gizmos As DockHelperGrid.VisibleGizmos)
        helperGridWindow.Mask(gizmos)
    End Sub





    Public Class MainDockGridToken
        Public MDG As MainDockGrid
        Public Sub New(ByRef _mdg As MainDockGrid)
            MDG = _mdg
        End Sub

        Public Sub Dispose()
            MDG = Nothing
            GC.SuppressFinalize(Me)
        End Sub
    End Class

    Public Class DockHelperInterface : Inherits Window


        Public DHG As DockHelperGrid
        Public MDG As MainDockGrid
        Public Sub New(ByRef _mdg As MainDockGrid)
            MDG = _mdg

            WindowStyle = Windows.WindowStyle.None
            AllowsTransparency = True
            Background = Brushes.Transparent
            ShowInTaskbar = False
            'BorderBrush = Brushes.CornflowerBlue        
            'BorderThickness = New Thickness(1)

            AllowsTransparency = True
            Opacity = 0.7

            DHG = New DockHelperGrid(_mdg)
            Content = DHG

        End Sub

        Public Overloads Sub Show(ByVal LocationToScreen As Point)
            Left = LocationToScreen.X
            Top = LocationToScreen.Y
            MyBase.Show()
        End Sub

        Protected masked As Boolean = True
        Public Sub UnMask(ByVal LocationToScreen As Point, ByVal Size As Size, ByVal gizmos As DockHelperGrid.VisibleGizmos)

            If Not masked Then Return 'se la questa funzione viene chiamata ma DockHelperInterface è già visibile è inutile proseguire.

            masked = False
            Left = LocationToScreen.X
            Top = LocationToScreen.Y
            Width = Size.Width
            Height = Size.Height

            ' Opacity = 1
            Visibility = Windows.Visibility.Visible

            If Not IsLoaded Then
                ShowActivated = False
                Show()
            End If

            DHG.UnMask(gizmos)

        End Sub

        ''' <summary>
        ''' rende invisibile la finestra rendendola non-opaca
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Mask(ByVal gizmos As DockHelperGrid.VisibleGizmos)
            If Not IsLoaded And Not masked Then Return
            masked = True
            ' Opacity = 0
            Visibility = Windows.Visibility.Hidden

            DHG.Mask(gizmos)
        End Sub

        Public Sub Dispose()
            MDG = Nothing

        End Sub

        Private Sub DockHelperInterface_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
            Owner = MDG.ParentWindow
        End Sub
    End Class

    Public Class PinningGrid : Inherits Grid

        Public LRGrid As Grid
        Public TBGrid As Grid
        Public Base As Grid

        Public MDG As MainDockGrid

        Public SplitterL As GridSplitter
        Public SplitterR As GridSplitter
        Public SplitterT As GridSplitter
        Public SplitterB As GridSplitter


        Public CurrentlyVisibleGrid As KGrid
        Public Sub New(ByRef _mdg As MainDockGrid)

            MDG = _mdg

            LRGrid = New Grid
            TBGrid = New Grid
            Base = New Grid

            Base.Background = Brushes.Transparent
         

            Children.Add(Base)
            Children.Add(LRGrid)
            Children.Add(TBGrid)

            LRGrid.Visibility = Windows.Visibility.Collapsed
            TBGrid.Visibility = Windows.Visibility.Collapsed


            AddHandler Base.MouseEnter, AddressOf _onMouseEnter
            AddHandler Base.MouseDown, AddressOf _onMouseDown



            'LEFT-RIGHT GRID
            LRGrid.ColumnDefinitions.Add(New ColumnDefinition With {.Width = GridLength.Auto})
            LRGrid.ColumnDefinitions.Add(New ColumnDefinition With {.Width = New GridLength(1, GridUnitType.Star)})
            LRGrid.ColumnDefinitions.Add(New ColumnDefinition With {.Width = GridLength.Auto})

            SplitterL = _mdg.Yield_LeftRightGridSplitter()
            SplitterL.HorizontalAlignment = Windows.HorizontalAlignment.Right
            Grid.SetColumn(SplitterL, 0)
            LRGrid.Children.Add(SplitterL)

            SplitterR = _mdg.Yield_LeftRightGridSplitter()
            SplitterR.HorizontalAlignment = Windows.HorizontalAlignment.Left
            Grid.SetColumn(SplitterR, 2)
            LRGrid.Children.Add(SplitterR)




            'TOP-BOTTOM GRID
            TBGrid.RowDefinitions.Add(New RowDefinition With {.Height = GridLength.Auto})
            TBGrid.RowDefinitions.Add(New RowDefinition With {.Height = New GridLength(1, GridUnitType.Star)})
            TBGrid.RowDefinitions.Add(New RowDefinition With {.Height = GridLength.Auto})

            SplitterT = _mdg.Yield_TopBottomGridSplitter()
            SplitterT.VerticalAlignment = Windows.VerticalAlignment.Bottom
            Grid.SetRow(SplitterT, 0)
            TBGrid.Children.Add(SplitterT)

            SplitterB = _mdg.Yield_TopBottomGridSplitter()
            SplitterB.VerticalAlignment = Windows.VerticalAlignment.Top
            Grid.SetRow(SplitterB, 2)
            TBGrid.Children.Add(SplitterB)


            Visibility = Windows.Visibility.Collapsed



        End Sub

        Private Sub _onMouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
            If CurrentlyVisibleGrid IsNot Nothing Then
                If CurrentlyVisibleGrid.State.HasFlag(KGrid.KGridState.Soft) Then
                    CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
                    Visibility = Windows.Visibility.Collapsed
                End If

            End If
        End Sub

        Private Sub _onMouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
            If CurrentlyVisibleGrid IsNot Nothing Then
                CurrentlyVisibleGrid.Visibility = Windows.Visibility.Collapsed
            End If

            Visibility = Windows.Visibility.Collapsed
        End Sub
    End Class


End Class
